import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue')
    },
    {
      path: '/product/:id',
      name: 'product',
      component: () => import('../views/ProductDetailView.vue')
    },
    {
      path: '/cart',
      name: 'cart',
      component: () => import('../views/CartView.vue')
    },
    {
      path: '/order/confirm',
      name: 'orderConfirm',
      component: () => import('../views/OrderConfirmView.vue')
    },
    {
      path: '/orders',
      name: 'orders',
      component: () => import('../views/OrdersView.vue')
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('../views/ProfileView.vue')
    },
    // 团购活动相关路由
    {
      path: '/group-buy',
      name: 'groupBuy',
      component: () => import('../views/GroupBuyView.vue')
    },
    // 注意：这个路由必须放在 /group-buy/order/:id 之前，否则会被误匹配
    {
      path: '/group-buy/:id',
      name: 'groupBuyDetail',
      component: () => import('../views/GroupBuyDetailView.vue')
    },
    {
      path: '/group-order/:id',
      name: 'groupBuyOrder',
      component: () => import('../views/GroupBuyOrderView.vue')
    },
    {
      path: '/group-orders',
      name: 'groupOrders',
      component: () => import('../views/GroupBuyOrdersView.vue')
    },
    // 管理员路由
    {
      path: '/admin',
      redirect: '/admin/statistics',
      meta: { requiresAdmin: true }
    },
    {
      path: '/admin/statistics',
      name: 'statistics',
      component: () => import('../views/StatisticsView.vue'),
      meta: { requiresAdmin: true }
    },
    {
      path: '/admin/products',
      name: 'productManage',
      component: () => import('../views/ProductManageView.vue'),
      meta: { requiresAdmin: true }
    },
    {
      path: '/admin/users',
      name: 'userManage',
      component: () => import('../views/UserManageView.vue'),
      meta: { requiresAdmin: true }
    }
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const userInfo = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null
  
  // 需要管理员权限的路由
  if (to.meta.requiresAdmin) {
    if (!token) {
      next({ name: 'login', query: { redirect: to.fullPath } })
      return
    }
    
    // 检查是否有管理员角色
    const isAdmin = userInfo && userInfo.roles && userInfo.roles.includes('ADMIN')
    if (!isAdmin) {
      alert('您没有权限访问该页面')
      next({ name: 'home' })
      return
    }
  }
  
  next()
})

export default router
